package com.tl.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * TimeUtils
 * 
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-8-24
 */
public class TimeUtils {

	public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	public static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat(
			"yyyy-MM-dd");
	
	


	/**
	 * long time to string
	 * 
	 * @param timeInMillis
	 * @param dateFormat
	 * @return
	 */
	public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
		return dateFormat.format(new Date(timeInMillis));
	}

	/**
	 * long time to string, format is {@link #DEFAULT_DATE_FORMAT}
	 * 
	 * @param timeInMillis
	 * @return
	 */
	public static String getTime(long timeInMillis) {
		return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
	}

	/**
	 * get current time in milliseconds
	 * 
	 * @return
	 */
	public static long getCurrentTimeInLong() {
		return System.currentTimeMillis();
	}

	/**
	 * get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT}
	 * 
	 * @return
	 */
	public static String getCurrentTimeInString() {
		return getTime(getCurrentTimeInLong());
	}

	/**
	 * get current time in milliseconds
	 * 
	 * @return
	 */
	public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
		return getTime(getCurrentTimeInLong(), dateFormat);
	}

	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 *            日期字符串 format 格式
	 * @return
	 */
	public static Date toDate(String sdate, SimpleDateFormat format) {
		if (StringUtils.isEmpty(sdate))
			return null;
		try {
			Date date = format.parse(sdate);
			return date;
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 获取日期和当前日期差值的,负数n天前,正数n天后
	 * 
	 * @param date
	 *            传入的日期
	 * @return
	 */
	public static int getDiff(String date, SimpleDateFormat dateforamt) {

		Calendar cal = Calendar.getInstance();
		Date time = toDate(date, dateforamt);

		// String curDate = dateFormater2.get().format(cal.getTime());
		// String paramDate = dateFormater2.get().format(date);

		long lt = time.getTime() / 86400000;
		long ct = cal.getTimeInMillis() / 86400000;
		int days = (int) (lt - ct) + 1;

		return days;
	}

	/**
	 * 获取和当前日期差值的日期
	 * 
	 * @param diff
	 *            负数n天前,正数n天后
	 * @return
	 */
	public static String getDataDiff(int diff, SimpleDateFormat dateforamt) {

		Calendar rightNow = Calendar.getInstance();
		// rightNow.add(Calendar.DAY_OF_MONTH,-1);
		rightNow.add(Calendar.DAY_OF_MONTH, diff);

		
		String ret = dateforamt.format(rightNow.getTime());
		return ret;

	}
}
